package myJs

import japgolly.scalajs.react.vdom.all.s
import myJs.myPkg.{ColumnOptions, LayerOptions, Select2Options, TableOptions}
import myJs.myPkg.jquery._

import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._
import myJs.Utils._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import shared.VarTool

import js.Dynamic.{global => g}
import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.JSON

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("Browse")
object Browse {

  @JSExport("init")
  def init = {
    refreshSamplesMethod
    refreshDiffSamplesMethod
    val index = layer.load(0, Tool.layerOptions.shade(js.Array("0.1", "#fff")))
    CircRnaBrowse.init.zip(PathwayBrowse.init).zip(CellBrowse.init).zip(MrnaBrowse.init).map { x =>
      layer.close(index)
    }

    registerEvent
    showTab
  }

  def refreshSamplesMethod = {
    val data = SeqMap("union" -> "Union", "inter" -> "Intersection")
    val array = data.map { case (id, text) =>
      js.Dictionary("text" -> text, "id" -> id)
    }
    val options = Select2Options.dictData(array.toJSArray)
    Tool.getInputByName("samplesMethod").select2(options)
  }

  def refreshDiffSamplesMethod = {
    val data = SeqMap("union" -> "Union", "inter" -> "Intersection")
    val array = data.map { case (id, text) =>
      js.Dictionary("text" -> text, "id" -> id)
    }
    val options = Select2Options.dictData(array.toJSArray)
    Tool.getInputByName("diffSamplesMethod").select2(options)
  }

  def getKind = {
    g.kind.toString
  }

  def showTab = {
    getKind match {
      case VarTool.circRnaKind => Tool.selectTab(CircRnaBrowse.tabId)
      case VarTool.lncRnaKind =>
        $(s"#${MrnaBrowse.tabId}").findInputByName("geneType").`val`("lncRNA gene")
        MrnaBrowse.mySearch
      case VarTool.mRnaKind =>
        $(s"#${MrnaBrowse.tabId}").findInputByName("geneType").`val`("protein coding gene")
        MrnaBrowse.mySearch
      case VarTool.pathwayKind =>
        Tool.selectTab(PathwayBrowse.tabId)
      case _ =>
    }
  }

  def selectOne(y: Element) = {
    val value = $(y).`val`()
    if ($(y).isChecked) {
      $(s"input:checkbox[value!='${value}']").setChecked(false)
    }
  }

  def registerEvent = {
    $(document.body).on("click", s"#mRna .mySelectOne", "", (y: Element) => {
      selectOne(y)
    })
  }

}
